package org.example.leetcpde;

import org.junit.jupiter.api.Test;

import java.util.HashMap;
import java.util.Map;

class Solution {
    @Test
    void aa() {
        int i = myAtoi("-91283472332");
        System.out.println(i);
    }

    public int myAtoi(String s) {
        class Automation {
            enum State {
                START, SIGNED, NUMBER, END;
            }

            Map<State, State[]> map = new HashMap<>() {{
                put(State.START, new State[]{State.START, State.SIGNED, State.NUMBER, State.END});
                put(State.SIGNED, new State[]{State.END, State.END, State.NUMBER, State.END});
                put(State.NUMBER, new State[]{State.END, State.END, State.NUMBER, State.END});
                put(State.END, new State[]{State.END, State.END, State.END, State.END});
            }};

            State state = State.START;
            int sign = 1;
            long num = 0;

            int getCol(char c) {
                if (c == ' ') {
                    return 0;
                }

                if (c == '+' || c == '-') {
                    return 1;
                }

                if (Character.isDigit(c)) {
                    return 2;
                }

                return 3;
            }

            void get(char c) {
                State[] states = map.get(state);
                int col = getCol(c);
                state = states[col];
                if (state == State.NUMBER) {
                    num = num * 10 + c - '0';
                    num = sign == 1 ? Math.min(num, Integer.MAX_VALUE) : Math.min(num, -(long) Integer.MIN_VALUE);
                }

                if (state == State.SIGNED) {
                    sign = c == '+' ? 1 : -1;
                }
            }
        }

        Automation automation = new Automation();
        for (char c : s.toCharArray()) {
            automation.get(c);
        }

        return (int) (automation.sign * automation.num);
    }
}